﻿(function ($) {
    //用于处理单个文件的上传
    $.imageUploader = function (options) {
        var defaultOpt = {
            urlOrFile: "",
            forceCrop: false,
            cropSize: null,  //{width:"500px",height:"500px"}
            maxFileSize: -1,
            uploadUrl: "",
            fieldName: "",
            onAfterSelectFile:null,
            onComplete:null,
            onSuccessCallback: null,
            onFailCallback: null,
            onPreview: null,  //上传前/上传后的预览回调
            onBeforeUpload: null,
            accept:"image/*",
            //fileField: null,  //如果需要指定特定的input file,,则在此设置,但,如果是需要强制裁剪的话,不会改变该file字段的数据内容,请在onSuccessCallback中读取
            sender: $(this)
        }

        var opt = $.extend({}, defaultOpt, options);

        var autoRemoveFileField = false;

        if (!opt.urlOrFile || isEmpty(opt.urlOrFile)) {
            var file = $('<input style="display:none" accept="' + opt.accept + '" type="file" name="' + opt.fieldName + '"/>');

            $(opt.sender).closest("div").append(file);
            //$(opt.sender).closest(".control-content").append(file);
             
            opt.urlOrFile = file;

            autoRemoveFileField = true;
        }

        var uploadFile = function(f, options) {
            var file = $(opt.urlOrFile);

            if ($(opt.urlOrFile).is("input[type=file]")) {
                file = opt.urlOrFile[0].files[0];
            } else {
                if (file.length && file.length>0) {
                    file = file[0];
                }
            }

            var fileName = file.name;
            file.name = fileName.substr(0, fileName.lastIndexOf('.')) + fileName.substring(fileName.indexOf('.') + 1);
            var progress = WebUIJS.ShowProgress(file.name);



            if (opt.onBeforeUpload) {
                __callBackFuncOrStr(opt.onBeforeUpload, opt.sender, [f]);
            }

            __uploadFileToServer(f,
                options.uploadUrl,
                {
                    fieldName: options.fieldName,
                    name: file.name,
                    onProgress: function (value) {
                        progress.setProgress(value);
                    },
                    onSuccess: function (data) {
                        if (options.onSuccessCallback) {
                            __callBackFuncOrStr(options.onSuccessCallback,
                                options.sender,
                                [data, f.name]);
                        }
                        
                        progress.hide();

                    },
                    onComplete: function(data) {
                        if (opt.onCompeted) {
                            __callBackFuncOrStr(opt.onCompeted, opt.sender, [data]);
                        }

                        if (autoRemoveFileField) {
                            opt.urlOrFile.remove();
                        }
                    },
                    onError: function () {
                        if (options.onFailCallback) {
                            __callBackFuncOrStr(options.onFailCallback,
                                options.sender,
                                []);
                        }
                    }
                });
        }

        var onPreview = function(base64) {
            if (opt.onPreview) {
                __callBackFuncOrStr(opt.onPreview,
                    opt.sender,
                    [base64]);
            }
        }

        var crop = function(urlOrFile, options) {
            $(opt.sender).imageCrop({
                urlOrFile: urlOrFile,
                cropSize: options.cropSize,
                onSuccessCallback: function (blob) {
                    uploadFile(blob, options);
                },
                sender: opt.sender,
                onPreview: opt.onPreview==null?null:onPreview,
                onFailCallback: function () {
                    if (options.onFailCallback) {
                        __callBackFuncOrStr(options.onFailCallback, options.sender, []);
                    }
                }
            });
        }

        if (opt.uploadUrl && opt.uploadUrl != "") {
            if (isString(opt.urlOrFile)) {
                crop(opt.urlOrFile, opt);
            } else if ($(opt.urlOrFile).is("input[type=file]")) {
                opt.urlOrFile[0].onchange = function(event) {
                    if (this.files.length <= 0) { //未选中任何文件
                        $(this).remove();
                        return false;
                    }

                    if (opt.maxFileSize && opt.maxFileSize > 0 && opt.fileField[0].files[0].size > opt.maxFileSize) {
                        $(this).remove();
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    if (opt.onAfterSelectFile) {
                        __callBackFuncOrStr(opt.onAfterSelectFile, this, [this]);
                    }

                    var file = this.files[0];

                    try {

                        if (opt.forceCrop && opt.cropSize != null && opt.cropSize.width > 0 && opt.cropSize.height > 0
                        ) { //如果需要强制裁剪的

                            crop(file, options);
                        } else {
                            if (opt.onPreview) {
                                __onReadFile(file,
                                    opt.sender,
                                    function(evt) {
                                        __callBackFuncOrStr(opt.onPreview, opt.sender, [evt.target.result]);
                                    });
                            }

                            uploadFile(file, opt);
                        }

                    } catch (e) {
                        //image.attr('src', $(this).val());
                        WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                        opt.urlOrFile.remove();
                        //return;
                    }
                }

                opt.urlOrFile.click();
            } else {
                if (opt.forceCrop && opt.cropSize != null && opt.cropSize.width > 0 && opt.cropSize.height > 0
                ) { //如果需要强制裁剪的

                    crop(opt.urlOrFile, options);
                } else {
                    if (opt.onPreview) {
                        __onReadFile(opt.urlOrFile,
                            opt.sender,
                            function(evt) {
                                __callBackFuncOrStr(opt.onPreview, opt.sender, [evt.target.result]);
                            });
                    }

                    uploadFile(opt.urlOrFile, opt);
                }
            }
        } else {

            var file = $(opt.urlOrFile);

            if ($(opt.urlOrFile).is("input[type=file]")) {
                file = opt.urlOrFile[0];
            } else {
                if (file.length && file.length > 0) {
                    file = file[0];
                }
            }

            file.name = opt.fieldName;

            file.onchange = function() {
                if (this.files.length <= 0) { //未选中任何文件
                    $(this).remove();
                    return false;
                }

                if (opt.maxFileSize && opt.maxFileSize > 0 && file.files[0].size > opt.maxFileSize) {
                    $(this).remove();
                    WebUIJS.Alert("文件太大,不能上传");
                    return false;
                }

                if (opt.onAfterSelectFile) {
                    __callBackFuncOrStr(opt.onAfterSelectFile, this, [this]);
                }

                try {
                    if (opt.onPreview) {
                        __onReadFile(file,
                            opt.sender,
                            function (evt) {
                                __callBackFuncOrStr(opt.onPreview, opt.sender, [evt.target.result]);
                            });
                    }
                } catch (e) {
                    WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                    file.remove();
                } 

            }

            file.click();
        }


        
        
    }

})(jQuery);